<script setup lang="jsx">
import { ref, computed, watch } from 'vue'
import { useRouter, RouterView } from 'vue-router'
import DraggableModal from '@/components/DraggableModal.vue'
import { NForm, NFormItem, NInput, NButton, NColorPicker, useMessage } from 'naive-ui'
import { globalVariable } from '@/stores/index.js'

const message = useMessage()
// 初始化路由
const router = useRouter()
// 获取全局变量store
const store = globalVariable()

// 模拟数据 - 导航菜单
const navItems = [
  {
    id: 'dashboard',
    name: '仪表盘',
    icon: '📊',
    path: '/admin/dashboard'
  },
  {
    id: 'tasks',
    name: '任务管理',
    icon: '📝',
    path: '/admin/tasks'
  },
  {
    id: 'schedule',
    name: '日程安排',
    icon: '📅',
    path: '/admin/schedule'
  },
  {
    id: 'notes',
    name: '笔记',
    icon: '📓',
    path: '/admin/notes'
  },
  {
    id: 'projects',
    name: '项目',
    icon: '📋',
    path: '/admin/projects'
  },
  {
    id: 'team',
    name: '团队',
    icon: '👥',
    path: '/admin/team'
  }
]

// 渲染标签选项的自定义样式
const renderTagLabel = (option) => {
  const category = store.getCategoryByName(option.name)
  const color = category?.color || 'default'
  return (
    <div class="flex items-center">
      <div class={`w-3 h-3 rounded-full mr-2`} style={`background: ${color}`}></div>
      <span>{option.name}</span>
    </div>
  )
}

// 当前激活的导航项
const activeNav = ref('dashboard')
// 前一个激活的导航项
const previousNav = ref('dashboard')
// 动画方向：'forward' (往左翻) 或 'backward' (往右翻)
const transitionDirection = ref('')

// 导航点击处理
const handleNavClick = async ({ id, path }) => {
  const currentIndex = navItems.findIndex(item => item.id === activeNav.value)
  const targetIndex = navItems.findIndex(item => item.id === id)
  
  // 设置动画方向
  transitionDirection.value = targetIndex > currentIndex ? 'forward' : 'backward'
  
  // 强制重新渲染以触发动画
  await setTimeout(() => {
    transitionDirection.value = ''
  }, 500)
  previousNav.value = activeNav.value
  activeNav.value = id
  router.push(path)
}

// 监听路由变化，处理浏览器前进后退按钮
watch(() => router.currentRoute.value.path, async (newPath, oldPath) => {
  const currentItem = navItems.find(item => item.path === newPath)
  const oldItem = navItems.find(item => item.path === oldPath)
  
  if (currentItem && oldItem) {
    const currentIndex = navItems.findIndex(item => item.id === currentItem.id)
    const oldIndex = navItems.findIndex(item => item.id === oldItem.id)
    
    // 设置动画方向
    transitionDirection.value = currentIndex > oldIndex ? 'forward' : 'backward'
    
    activeNav.value = currentItem.id
  }
})

// 分类点击处理
const handleCategoryClick = (categoryId) => {
  // 可以在这里添加分类筛选逻辑
  console.log('选择分类:', categoryId)
}

// 添加分类模态框控制
const showAddCategoryModal = ref(false)
const addCategoryFormRef = ref(null)
const newCategory = ref({
  name: '',
  color: '#165DFF'
})
const categoryRules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { max: 20, message: '分类名称不能超过20个字符', trigger: 'blur' }
  ]
}

// 快速添加任务模态框控制
const showQuickAddTaskModal = ref(false)
const quickAddTaskFormRef = ref(null)
const quickTask = ref({
  title: '',
  categoryId: ''
})
const quickTaskRules = {
  title: [
    { required: true, message: '请输入任务标题', trigger: 'blur' },
    { max: 50, message: '任务标题不能超过50个字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择任务分类', trigger: 'change' }
  ]
}

// 添加分类处理
const addCategory = () => {
  showAddCategoryModal.value = true
}

// 处理添加分类表单提交
const handleAddCategory = async () => {
  if (!addCategoryFormRef.value) return
  
  try {
    await addCategoryFormRef.value.validate()
    
    // 添加新分类
    store.addCategory(newCategory.value)
    
    // 重置表单
    addCategoryFormRef.value.restoreValidation()
    newCategory.value = {
      name: '',
      color: '#165DFF'
    }
    
    // 关闭模态框
    showAddCategoryModal.value = false
    
    // 显示成功提示
    message.success('分类添加成功！')
  } catch (error) {
    // 表单验证失败
    console.log('表单验证失败:', error)
  }
}

// 快速添加任务处理
const quickAddTask = () => {
  showQuickAddTaskModal.value = true
}

// 处理快速添加任务表单提交
const handleQuickAddTask = async () => {
  if (!quickAddTaskFormRef.value) return
  
  try {
    await quickAddTaskFormRef.value.validate()
    
    // 找到对应的分类并增加任务数
    store.incrementCategoryCount(quickTask.value.categoryId)
    
    // 重置表单
    quickAddTaskFormRef.value.restoreValidation()
    quickTask.value = {
      title: '',
      categoryId: ''
    }
    
    // 关闭模态框
    showQuickAddTaskModal.value = false
    
    // 显示成功提示
    message.success('任务添加成功！')
  } catch (error) {
    // 表单验证失败
    console.log('表单验证失败:', error)
  }
}
</script>

<template>
  <div class="admin-layout">
    <!-- 左侧导航栏 -->
    <aside class="sidebar">
      <!-- 导航菜单 -->
      <nav class="nav-menu">
        <h2 class="nav-title">主菜单</h2>
        <ul class="nav-list">
          <li
            v-for="item in navItems"
            :key="item.id"
            class="nav-item"
            :class="{ active: activeNav === item.id }"
            @click="handleNavClick(item)"
          >
            <span class="nav-icon">{{ item.icon }}</span>
            <span class="nav-text">{{ item.name }}</span>
          </li>
        </ul>
      </nav>

      <!-- 任务分类 -->
      <div class="task-categories">
        <h2 class="categories-title">任务分类</h2>
        <ul class="categories-list">
          <li
            v-for="category in store.categories"
            :key="category.id"
            class="category-item"
            @click="handleCategoryClick(category.id)"
          >
            <span 
              class="category-color"
              :style="{ backgroundColor: category.color }"
            ></span>
            <span class="category-name">{{ category.name }}</span>
            <span class="category-count">{{ category.count }}</span>
          </li>
          <li class="category-item add-category" @click="addCategory">
            <span class="category-icon">+</span>
            <span class="category-name">添加分类</span>
          </li>
        </ul>
      </div>

      <!-- 快速添加任务按钮 -->
      <div class="quick-add">
        <button class="add-btn" @click="quickAddTask">
          <span class="add-icon">+</span>
          <span class="add-text">快速添加任务</span>
        </button>
      </div>
    </aside>

    <!-- 右侧内容区域 -->
    <main class="content">
      <Transition name="slide-fade" mode="out-in">
        <RouterView />
      </Transition>
    </main>

    <!-- 添加分类模态框 -->
    <DraggableModal 
      v-model:visible="showAddCategoryModal" 
      title="添加分类" 
      width="400px"
      :initial-position="{ top: '50%', left: '50%' }"
      draggable
      show-close
    >
      <div class="p-2">
        <n-form ref="addCategoryFormRef" :model="newCategory" :rules="categoryRules" class="space-y-4">
          <n-form-item label="分类名称" path="name" :label-style="{ color: '#fff' }">
            <n-input 
              v-model:value="newCategory.name" 
              placeholder="请输入分类名称"
              :style="{ backgroundColor: 'rgba(255, 255, 255, 0.1)', borderColor: 'rgba(127, 219, 255, 0.3)', color: '#fff' }"
            />
          </n-form-item>
          
          <n-form-item label="分类颜色" path="color" :label-style="{ color: '#fff' }">
            <n-color-picker 
              v-model:value="newCategory.color" 
              :style="{ backgroundColor: 'rgba(255, 255, 255, 0.1)', borderColor: 'rgba(127, 219, 255, 0.3)' }"
            />
          </n-form-item>
        </n-form>
      </div>
      <template #footer>
        <n-button type="default" @click="showAddCategoryModal = false" :style="{ color: '#0074d9', borderColor: '#0074d9' }">取消</n-button>
        <n-button type="primary" @click="handleAddCategory" :style="{ backgroundColor: '#0074d9', borderColor: '#0074d9' }">创建</n-button>
      </template>
    </DraggableModal>

    <!-- 快速添加任务模态框 -->
    <DraggableModal 
      v-model:visible="showQuickAddTaskModal" 
      title="快速添加任务" 
      width="400px"
      :initial-position="{ top: '50%', left: '50%' }"
      draggable
      show-close
    >
      <div class="p-2">
        <n-form ref="quickAddTaskFormRef" :model="quickTask" :rules="quickTaskRules" class="space-y-4">
          <n-form-item label="任务标题" path="title" :label-style="{ color: '#fff' }">
            <n-input 
              v-model:value="quickTask.title" 
              placeholder="请输入任务标题"
              :style="{ backgroundColor: 'rgba(255, 255, 255, 0.1)', borderColor: 'rgba(127, 219, 255, 0.3)', color: '#fff' }"
            />
          </n-form-item>
          
          <n-form-item label="任务分类" path="categoryId" :label-style="{ color: '#fff' }">
            <n-select 
              v-model:value="quickTask.categoryId" 
              placeholder="请选择分类"
              :options="store.categories"
              :style="{ backgroundColor: 'rgba(255, 255, 255, 0.1)', borderColor: 'rgba(127, 219, 255, 0.3)', color: '#fff' }"
              label-field="name"
              value-field="id"
              :render-label="renderTagLabel"
            />
          </n-form-item>
        </n-form>
      </div>
      <template #footer>
        <n-button type="default" @click="showQuickAddTaskModal = false" :style="{ color: '#0074d9', borderColor: '#0074d9' }">取消</n-button>
        <n-button type="primary" @click="handleQuickAddTask" :style="{ backgroundColor: '#0074d9', borderColor: '#0074d9' }">添加</n-button>
      </template>
    </DraggableModal>
  </div>
</template>

<style scoped lang="scss">
// 主布局
.admin-layout {
  display: flex;
  height: 100vh;
  background-color: var(--bg-primary);
  font-family: 'PingFang SC', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

// 侧边栏样式
sidebar {
  width: 240px;
  background-color: var(--bg-secondary);
  border-right: 1px solid var(--border-color);
  display: flex;
  flex-direction: column;
  padding: 20px 0;
  overflow-y: auto;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.06);
}

// 导航菜单样式
.nav-menu {
  flex: 0 0 auto;
}

.nav-title {
  font-size: 14px;
  font-weight: 500;
  color: var(--text-secondary);
  margin: 0 20px 12px;
  padding: 0;
}

.nav-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.nav-item {
  display: flex;
  align-items: center;
  padding: 12px 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  border-left: 3px solid transparent;
  margin-bottom: 2px;
}

.nav-item:hover {
  background-color: var(--hover-bg);
  color: var(--primary-color);
}

.nav-item.active {
  background-color: var(--hover-bg);
  color: var(--primary-color);
  border-left-color: var(--primary-color);
  font-weight: 500;
}

.nav-icon {
  font-size: 18px;
  margin-right: 10px;
  width: 20px;
  text-align: center;
}

.nav-text {
  font-size: 14px;
}

// 任务分类样式
.task-categories {
  flex: 0 0 auto;
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid var(--border-color);
}

.categories-title {
  font-size: 14px;
  font-weight: 500;
  color: var(--text-secondary);
  margin: 0 20px 12px;
  padding: 0;
}

.categories-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.category-item {
  display: flex;
  align-items: center;
  padding: 10px 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-bottom: 2px;
}

.category-item:hover {
  background-color: var(--hover-bg);
}

.category-color {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  margin-right: 8px;
  flex-shrink: 0;
}

.category-name {
  flex: 1;
  font-size: 14px;
  color: var(--text-primary);
}

.category-count {
  font-size: 12px;
  color: var(--text-secondary);
  background-color: #f0f0f0;
  padding: 2px 8px;
  border-radius: 10px;
  min-width: 20px;
  text-align: center;
}

.add-category {
  color: var(--primary-color);
}

.category-icon {
  font-size: 16px;
  font-weight: bold;
  margin-right: 8px;
  width: 12px;
  text-align: center;
}

// 快速添加按钮样式
.quick-add {
  flex: 0 0 auto;
  margin-top: auto;
  padding: 20px;
}

.add-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  padding: 12px 20px;
  background-color: var(--primary-color);
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(22, 93, 255, 0.3);
}

.add-btn:hover {
  background-color: #0948d9;
  box-shadow: 0 4px 12px rgba(22, 93, 255, 0.4);
  transform: translateY(-1px);
}

.add-btn:active {
  transform: translateY(0);
}

.add-icon {
  font-size: 16px;
  margin-right: 6px;
  font-weight: bold;
}

// 内容区域样式
.content {
  flex: 1;
  background-color: var(--bg-primary);
  position: relative;
  overflow: hidden;
}

.slide-fade-enter-active {
  transition: all 0.4s ease-out;
}

.slide-fade-leave-active {
  transition: all 0.01s ease-out;
}

.slide-fade-enter-from,
.slide-fade-leave-to {
  transform: translateX(-100%);
}

// 响应式设计
@media (max-width: 768px) {
  .sidebar {
    width: 200px;
  }
  
  .nav-text, .category-name, .add-text {
    font-size: 13px;
  }
  
  .nav-icon {
    font-size: 16px;
  }
}
</style>